<template>
    <el-dialog v-model="visible" :title="$t('修改报价')" :close-on-click-modal="false" :close-on-press-escape="false"
        style="width: 30%;top:12%;">
        <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
            label-width="100px">
            <el-form-item label="报价" prop="quotation">
                <el-input v-model="dataForm.quotation" placeholder="请输入"></el-input>
            </el-form-item>
        </el-form>
        <template v-slot:footer>
            <el-button @click="visible = false" class="quxiao">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const dataForm = reactive({
    id: "",
    quotation: "",
    quoted: 1
});

// 自定义验证器：检查是否为大于0的数字，且最多保留两位小数
const validateQuotation = (rule: any, value: string, callback: any) => {
    if (!value) {
        return callback(new Error(t("请输入大于0的数")));
    }

    // 使用正则表达式验证
    const regex = /^[+]?([1-9]\d*|0)(\.\d{1,2})?$/;
    if (!regex.test(value)) {
        return callback(new Error(t("请输入大于0的数")));
    }

    // 验证通过
    callback();
};

const rules = ref({
    quotation: [
        { validator: validateQuotation, trigger: "change" }
    ],
});
const init = (id?: number) => {
    visible.value = true;
    dataForm.id = "";

    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }
    if (id) {
      getInfo(id);
    }
};

const getInfo = (id: number) => {
  baseService.get(`/noc/productuserquotation/info/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
    dataFormRef.value.validate((valid: boolean) => {
        if (!valid) {
            return false;
        }
      dataForm.quoted = 1;
        (baseService.post)("/noc/productuserquotation/update", dataForm).then((res) => {
            ElMessage.success({
                message: t("prompt.success"),
                duration: 500,
                onClose: () => {
                    visible.value = false;
                    emit("refreshDataList");
                }
            });
        });
    });
};

defineExpose({
    init
});
</script>
<style>
.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
}
</style>
